package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.xn.app.muying.R;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.zhuge.analysis.stat.ZhugeSDK;

import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 个人信息页面
 * Created by gaoge on 2016/11/30.
 */

public class PersonalActivity extends BaseActivity {

    //返回键
    private ImageView img_back = null;
    //标题
    private TextView title_name = null;
    //姓名
    private EditText name = null;
    //身份证
    private EditText identity = null;
    //手机号
    private TextView phone = null;
    //确认按钮
    private Button button = null;
    //数据库
    private DBManager db = null;
    //记录数据库中姓名，身份证，手机号
    private String nameStr, identityStr, phoneStr;
    //记录文本框中姓名，身份证，手机号
    private String name1, identity1, phone1;
    //获取页面传来的数据
    private String type = "";
    //加载框
    AlertDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal);
        //初始化组件
        initialization();
        //实现
        realize();
    }

    /**
     * 初始化组件，并给相应控件添加单击事件
     * view
     */
    private void initialization() {
        try {
            ZhugeSDK.getInstance().track(getApplicationContext(), "个人信息完善");
        } catch (Exception e) {
            e.printStackTrace();
        }
        db = new DBManager(this);
        type = getIntent().getStringExtra("type");
        nameStr = db.select("name");
        phoneStr = db.select("tel");
        identityStr = db.select("identityId");
        title_name = (TextView) findViewById(R.id.title_name);
        name = (EditText) findViewById(R.id.name);
        identity = (EditText) findViewById(R.id.identity);
        phone = (TextView) findViewById(R.id.phone);
        button = (Button) findViewById(R.id.button);
        img_back = (ImageView) findViewById(R.id.img_back);
        //返回键点击
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (getBooLean()) {
                    getHint();
                } else {
                    finish();
                }
            }
        });
        //确认按钮点击
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                name1 = name.getText().toString();
                identity1 = identity.getText().toString();
                phone1 = phone.getText().toString();
                if (name1 != null && !name1.equals("") && !name1.equals("null")) {
                    if (name1.matches("^[\\u4e00-\\u9fa5]*$")) {
                        if (identity1 != null && !identity1.equals("") && !identity1.equals("null")) {
                            if (identity1.matches("[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$")) {
                                if (phone1 != null && !phone1.equals("") && !phone1.equals("null")) {
                                    if (getBooLean()) {
                                        //提交数据
                                        if (NetworkUtil.isNetworkAvailable(PersonalActivity.this)) {
                                            dialog = new MyAlertDialog().ShowDialog(PersonalActivity.this, R.layout.dialog_loading);
                                            setData();
                                        } else {
                                            ToastUtil.showToast(PersonalActivity.this, R.string.no_network_hint);
                                        }
                                    } else {
                                        finish();
                                    }
                                } else {
                                    ToastUtil.showToast(PersonalActivity.this, "请完善手机号后再保存");
                                }
                            } else {
                                ToastUtil.showToast(PersonalActivity.this, "请正确填写的身份证号");
                            }
                        } else {
                            ToastUtil.showToast(PersonalActivity.this, "请完善身份证号后再保存");
                        }
                    } else {
                        ToastUtil.showToast(PersonalActivity.this, "请正确填写姓名");
                    }
                } else {
                    ToastUtil.showToast(PersonalActivity.this, "请完善姓名后再保存");
                }
            }
        });
    }

    /**
     * 功能实现
     */
    private void realize() {
        //设置标题
        if (type.equals("0")) {
            title_name.setText("个人信息");
        } else {
            title_name.setText("完善个人信息");
        }
        //设置姓名
        if (nameStr != null && !nameStr.equals("") && !nameStr.equals("null") && nameStr.matches("^[\\u4e00-\\u9fa5]*$")) {
            name.setText(nameStr);
            name.setSelection(nameStr.length());
        } else {
            name.setText("");
        }
        //设置电话
        if (phoneStr != null && !phoneStr.equals("") && !phoneStr.equals("null")) {
            phone.setText(phoneStr.replaceAll("(\\d{3})\\d{5}(\\d{3})", "$1*****$2"));
        } else {
            phone.setText("");
        }
        //设置身份证
        if (identityStr != null && !identityStr.equals("") && !identityStr.equals("null")) {
            identity.setText(identityStr);
            identity.setSelection(identity.length());
        } else {
            identity.setText("");
        }
    }

    /**
     * 验证是否修改过
     */
    private boolean getBooLean() {
        //记录是否修改过数据
        boolean lean = false;
        if (nameStr.equals(name.getText().toString())) {
            lean = false;
            if (identityStr.equals(identity.getText().toString())) {
                lean = false;
            } else {
                lean = true;
            }
        } else {
            lean = true;
        }
        return lean;
    }

    /**
     * 提交数据
     */
    private void setData() {
        //热门标签
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HashMap<String, String> param = new HashMap<>();
                    param.put("identityId", identity1);
                    param.put("name", name1);
                    String p = new Gson().toJson(param);
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url(APIMethod.PeronalSubmit).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).put(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    if (code == 200 || code == 204) {
                        loginHandler.sendEmptyMessage(1);
                    } else {
                        loginHandler.sendEmptyMessage(2);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {

            if (dialog != null) {
                dialog.dismiss();
            }
            switch (msg.what) {
                //成功
                case 1:
                    //修改数据库中用户信息相关字段
                    db.updateUserNameOrIdentity(identity1, name1, phoneStr);
                    ToastUtil.showToast(PersonalActivity.this, "提交成功");
                    finish();
                    break;
                //失败
                case 2:
                    ToastUtil.showToast(PersonalActivity.this, "提交失败");
                    break;
                default:
                    break;
            }
        }
    };

    //加载框
    MyAlertDialog dialog1;

    /**
     * 提示是否返回
     */
    private void getHint() {
        try {
            //加载弹出框
            dialog1 = new MyAlertDialog();
            dialog1.Prompt_Dialog(PersonalActivity.this, R.layout.prompt_dialog);
            //设置内容
            TextView data = dialog1.getData();
            data.setText("是否放弃编辑并退出？");
            //设置取消按钮
            TextView getCancel_text = dialog1.getCancel_text();
            getCancel_text.setText("取消");
            getCancel_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog1.dismiss();
                }
            });
            //设置确认按钮
            TextView getConfirm_text = dialog1.getConfirm_text();
            getConfirm_text.setText("确定");
            getConfirm_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog1.dismiss();
                    finish();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (getBooLean()) {
                getHint();
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
